package com.timothy.android;

import com.timothy.android.util.ActivityStackControlUtil;
import com.timothy.service.BackLightService;
import com.timothy.service.CommunicationService;
import com.timothy.service.MessageSenderUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.app.NotificationManager;

public abstract class BaseActivity extends Activity {
	private static final String LOG_TAG = "BaseActivity";
	public static final int ITEM0 = Menu.FIRST;
	public static final int ITEM1 = Menu.FIRST + 1;
	public static final int ITEM2 = Menu.FIRST + 2;
	public static final int ITEM3 = Menu.FIRST + 3;
	
	public int screenHeight ;	
	public int screenWidth ;
	public int screenSize;
	
	public int statusBarHeight;
	public int titleBarHeight;
	
	
	public float screenStartBrightness;
	public SharedPreferences sharedPreferences;
	
	//screen brightness monitor
	private Messenger bsrMessenger = new Messenger( new BSIncomingHandler() );
    private Messenger bssMessenger = null;	
    
//    //message receive 
//    private Messenger rsrMessenger = new Messenger( new RSIncomingHandler() );
//    private Messenger rssMessenger = null;
//    
//    //call and sms block 
//    private Messenger blkRMessenger = new Messenger(new BLKIncomingHandler() );
//    private Messenger blkSMessenger = null;
    
	public float getScreenStartBrightness() {
		return screenStartBrightness;
	}

	public void setScreenStartBrightness(float screenStartBrightness) {
		this.screenStartBrightness = screenStartBrightness;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		ActivityStackControlUtil.add(this);
		
		getAllScreenValues();
		
	    //keep screen no locked
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        //set background picture
//        setBgPic();
        
        //set default orientation
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        //show mobile ip
        
//        this.setTitleColor(Color.GREEN);
 
		//record screen start brightness
	    WindowManager.LayoutParams lp = getWindow().getAttributes();     
	    setScreenStartBrightness(lp.screenBrightness);		      
	    Log.i(LOG_TAG,"Screen Start Brightness:" + getScreenStartBrightness());
	    
	    //get screen size
	    Display display = getWindowManager().getDefaultDisplay();
	    screenHeight = display.getHeight();
	    screenWidth = display.getWidth();
	    
	    Log.i(LOG_TAG,"screenHeight:" + screenHeight);
	    Log.i(LOG_TAG,"screenWidth:" + screenWidth);
	    
	    if(screenHeight >=800 && screenWidth >=480){
	    	screenSize = 1;
		}else if( screenHeight >= 480 && screenWidth>=320){
			screenSize = 2;
		}else{
			screenSize = 3;
		}
	    Log.i(LOG_TAG,"screenSize:" + screenSize);
	    
	    //bind screen brightness service
	    Log.i(LOG_TAG,"start bind services...");
	    
	    //status bar height
	    Rect frame = new Rect();   
	    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
	    statusBarHeight = frame.top;
	    Log.i(LOG_TAG,"statusBarHeight:" + statusBarHeight);

	    //title bar height
	    int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
	    titleBarHeight = contentTop - statusBarHeight;
	    Log.i(LOG_TAG,"titleBarHeight:" + titleBarHeight);
	    
	    
	    //get sharedPreferences
	    Log.i(LOG_TAG,"Get sharedPreferences.");
	    sharedPreferences = this.getSharedPreferences("powersmart",MODE_PRIVATE); 
	    
	    Log.i(LOG_TAG,"Begin Bind Service...");
	    
	    //when login page started, mobile is not connected with server
	    if(MessageSenderUtil.PC_IP==null){
	    	doBindOtherService();
	    }else{//for the left pages,mobile is connected with server
	    	doBindCommService();
	    	doBindOtherService();
	    }
	    
	}
	
	public void getAllScreenValues(){
		Rect frame = new Rect();  
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
		int statusBarHeight = frame.top; 
		Log.i(LOG_TAG,"statusBarHeight:" + statusBarHeight);
		
		int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
		int titleBarHeight = contentTop - statusBarHeight ;
		Log.i(LOG_TAG,"titleBarHeight:" + titleBarHeight);
	}

	public void recoverBrightness(){
		//恢复屏幕亮度
//		Log.i(LOG_TAG,"Recover Screen Start Brightness.");
//		Log.i(LOG_TAG,"Get Screen Start Brightness:" + getScreenStartBrightness());
		
		WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = getScreenStartBrightness();
        getWindow().setAttributes(lp);
        
        Message msg = Message.obtain(null, BackLightService.MSG_TOUCH_SCREEN);
        msg.replyTo = bsrMessenger;
        try {
        	bssMessenger.send(msg);
        } catch (RemoteException e) {
        }		
	}
	
	//touch screen event
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		recoverBrightness();
		return super.onTouchEvent(event);
	}

	protected void onDestroy() {
        super.onDestroy();
        doUnbindCommService();
        doUnbindOtherService();
        
        recoverBrightness();
    }
	
	private boolean blkIsBound;
	private boolean bsIsBound;
	private boolean rsIsBound;
	
	//-------------------start bind brightness service---------------------
	protected void doBindCommService() {
        Log.i(LOG_TAG,"start bind service CommunicationService...");
        bindService(new Intent(this, CommunicationService.class), commConnection, Context.BIND_AUTO_CREATE);
    }
	
	protected void doBindOtherService() {
	    Log.i(LOG_TAG,"start bind service BackLightService...");
        bindService(new Intent(this, BackLightService.class), bsConnection, Context.BIND_AUTO_CREATE);
    }

	protected void doUnbindCommService() {
        if (eneterIsBound) {
        	eneterIsBound = false;
        }
    }
	
	protected void doUnbindOtherService() {
        if (bsIsBound) {
            unbindService(bsConnection);
        }
    }
	
	private ServiceConnection bsConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	 bssMessenger = new Messenger(service);
             try {
                 Message msg = Message.obtain(null, BackLightService.MSG_REGISTER_CLIENT);
                 msg.replyTo = bsrMessenger;
                 bssMessenger.send(msg);
             } catch (RemoteException e) {
             }
        
            bsIsBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
        	 Message msg = Message.obtain(null, BackLightService.MSG_UNREGISTER_CLIENT);
             msg.replyTo = bsrMessenger;
             try {
            	 bssMessenger.send(msg);
            	 bsIsBound = false;
             } catch (RemoteException e) {
             }
        }
    };
    
    /*private ServiceConnection rsConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	 Log.i(LOG_TAG,"ServiceConnection.onServiceConnected()...");
        	 
        	 rssMessenger = new Messenger( service );
        	 
             // We want to monitor the service for as long as we are connected to it.
             try {
                 Message msg = Message.obtain(null, MessageReceiveService.MSG_REGISTER_CLIENT);
                 
                 Log.i(LOG_TAG,"msg.what:"+msg.what);
                 Log.i(LOG_TAG,"msg.replyTo:"+msg.replyTo);
                 Log.i(LOG_TAG,"msg.arg1:"+msg.arg1);
                 Log.i(LOG_TAG,"msg.arg2:"+msg.arg2);
                 
                 msg.replyTo = rsrMessenger;
                 rssMessenger.send(msg);
             } catch (RemoteException e) {
                 // In this case the service has crashed before we could even
                 // do anything with it; we can count on soon being
                 // disconnected (and then reconnected if it can be restarted)
                 // so there is no need to do anything here.
             }
        
            rsIsBound = true;
            // Tell the user about this for our demo.
//            Toast.makeText( getBaseContext(), R.string.message_receive_service_connected, Toast.LENGTH_SHORT).show();
        }
        
        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
        	 Message msg = Message.obtain(null, MessageReceiveService.MSG_UNREGISTER_CLIENT);
             msg.replyTo = rsrMessenger;
             try {
            	 rssMessenger.send(msg);
             } catch (RemoteException e) {
                 // In this case the service has crashed before we could even
                 // do anything with it; we can count on soon being
                 // disconnected (and then reconnected if it can be restarted)
                 // so there is no need to do anything here.
             }
            Toast.makeText( getBaseContext(), R.string.message_receive_service_disconnected, Toast.LENGTH_SHORT).show();
        }
    };*/
 
	
    
    class BSIncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BackLightService.MSG_DARK:
		        	//使屏幕的亮度变暗
		        	WindowManager.LayoutParams lp = getWindow().getAttributes();
	        		lp.screenBrightness = 0.2f;
		            getWindow().setAttributes(lp);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
    
    class RSIncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
        	Log.i(LOG_TAG,"RSIncomingHandler.handleMessage()...");
    		Log.i(LOG_TAG,""+msg.obj);
        	processMessage( msg.what, (String)msg.obj );
        }
    }
    
    class BLKIncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
    		Log.i(LOG_TAG,""+msg.obj);
        	processMessage( msg.what, (String)msg.obj );
        }
    }
    
    
    protected abstract void processMessage(int what,String content);
	
	//-------------------start create menu and add menu event---------------------
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, ITEM0, 0, "Setting");
		menu.add(0, ITEM1, 0, "Logout");
		menu.add(0, ITEM2, 0, "BaseStations");
		menu.add(0, ITEM3, 0, "Exit");
		menu.findItem(ITEM1);// 可以设置按钮的背景
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case ITEM0:actionClickMenuItem1();break;
			case ITEM1:actionClickMenuItem2();break;
			case ITEM2:actionClickMenuItem3();break;
			case ITEM3:actionClickMenuItem4();break;
		}
		return super.onOptionsItemSelected(item);
	}

	//Setting
	private void actionClickMenuItem1() {
	}

	//Logout
	private void actionClickMenuItem2() {
		finish();//finish current activity
		
		Intent intent = new Intent();
	    intent.setClass(this,LoginActivity.class);
	    startActivity(intent);
	}

	//About
	private void actionClickMenuItem3() {
		if(!sendMessage(MessageSenderUtil.addHeader(MessageSenderUtil.Get_Base_Stations))  ) {
			ShowDialog("Can not login Server!");
		}
	}

	//Exit
	private void actionClickMenuItem4() {
		
		AlertDialog.Builder dlg = new AlertDialog.Builder(this);
		dlg.setTitle(R.string.exit);
		dlg.setMessage(getResources().getString(R.string.wheter_to_exit))
			.setPositiveButton(getResources().getString(R.string.ok),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
							notificationManager.cancelAll();
//								Intent i = new Intent();
//								i.setClass(this,LoginActivity.class);
//								i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//								i.putExtra("autoLogin", false);
//								startActivity(i);
							
							//----before 2.2-----
//							ActivityManager am = (ActivityManager)getSystemService (Context.ACTIVITY_SERVICE);
//							am.restartPackage(getPackageName());
//							showDesk();
//							android.os.Process.killProcess(android.os.Process.myPid());
							
							finish();//finish current activity
							
							Intent mIntent = new Intent();
							mIntent.setClass(getBaseContext(), LoginActivity.class);
							mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							mIntent.putExtra("flag", 0x0001);
							startActivity(mIntent);

						}
					})
			.setNegativeButton(getResources().getString(R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
						}
					}).create().show();
	}
	//-------------------end create menu and add menu event---------------------
	
	//----Android 2.2
	public void showDesk(){
        //show desk
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addCategory(Intent.CATEGORY_HOME);
        startActivity(i); 
	}
	
	public void ShowDialog(String msg) {
		new AlertDialog.Builder(this).setTitle("Note").setMessage(msg)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
		}).show();
	}
	
	
	private long exitTime = 0;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "Click again to quit!",Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				ActivityStackControlUtil.finishProgram();
				System.exit(0);
				
				Intent mIntent = new Intent();
				mIntent.setClass(getBaseContext(), LoginActivity.class);
				mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				mIntent.putExtra("flag", 0x0001);
				startActivity(mIntent);
			}
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	//===========================eneter start================================
	
    //message receive 
    private Messenger eneterRMessenger = new Messenger( new EneterIncomingHandler() );
    private Messenger eneterSMessenger = null;
    private boolean eneterIsBound;
    public int connectedWithEneter = 1;
    
	private ServiceConnection commConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
        	eneterSMessenger = new Messenger( service );
            try {
                Message msg = Message.obtain(null, CommunicationService.MSG_REGISTER_CLIENT);
                msg.replyTo = eneterRMessenger;
                eneterSMessenger.send(msg);
            } catch (RemoteException e) {
            }
            
            eneterIsBound = true;
            
            Log.i(LOG_TAG,"Comm Service Connected..." + connectedWithEneter++);
       }
       
       public void onServiceDisconnected(ComponentName className) {
       	 	Message msg = Message.obtain(null, CommunicationService.MSG_UNREGISTER_CLIENT);
            msg.replyTo = eneterRMessenger;
            try {
            	eneterSMessenger.send(msg);
            	eneterIsBound = false;
            	Log.i(LOG_TAG,"Comm Service Disonnected..." + connectedWithEneter);
            } catch (RemoteException e) {
            }
       }
    };
    
    public boolean sendMessage(String command){
    	Log.i(LOG_TAG, "command:"+command);
    	Message msg = Message.obtain(null,CommunicationService.MSG_SEND_SERVER,command);
        try {
        	eneterSMessenger.send(msg);
			Log.i(LOG_TAG, "CommunicationService.MSG_SEND_SERVERE=" + CommunicationService.MSG_SEND_SERVER);
		} catch (RemoteException e) {
			Log.i(LOG_TAG, "RemoteException:"+e.getMessage());
		}
    	return true;
    }
    
    class EneterIncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
    		Log.i(LOG_TAG,"EneterIncomingHandler.handleMessage() Start...");
        	processMessage( msg.what, (String)msg.obj );
        	Log.i(LOG_TAG,"msg.what="+msg.what);
        	Log.i(LOG_TAG,"msg.obj="+msg.obj);
        	Log.i(LOG_TAG,"EneterIncomingHandler.handleMessage() End.");
        }
    }
    
  //===========================eneter end================================
}
